<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="value"
      width="1200px"
      append-to-body
      custom-class="import-dialog"
      @close="close"
    >
      <div class="form-box">
        <el-form
          :model="form"
          :rules="rules"
          ref="form"
          label-width="120px"
          class="add-form"
        >
          <div class="section">
            <el-descriptions title="基本信息"></el-descriptions>
            <el-form-item label="签约方式" prop="orderLessee.lesseeType">
              <el-radio-group v-model="form.orderLessee.lesseeType" :disabled="isRelet">
                <el-radio label="1">个人签约</el-radio>
                <el-radio label="2">企业签约</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div class="section">
            <el-descriptions title="房源信息"></el-descriptions>
            <el-form-item label="房间" prop="premisesAddress">
              <el-button
                size="small"
                type="primary"
                icon="el-icon-s-home"
                :disabled="isRelet"
                @click="dialogSelectHouseVisible = true"
                >选择房屋</el-button
              >
              <el-input
                style="width: 200px; margin-left: 10px"
                v-model="form.premisesAddress"
                placeholder="请选择房屋"
                readonly
              ></el-input>
            </el-form-item>
          </div>
          <el-descriptions title="承租人信息"></el-descriptions>
          <el-row :gutter="10">
            <el-col :span="8" v-if="form.orderLessee.lesseeType == 2">
              <el-form-item label="企业名称" prop="orderLessee.enterpriseName">
                <el-input
                  placeholder="请输入"
                  v-model="form.orderLessee.enterpriseName"
                  style="width: 80%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="form.orderLessee.lesseeType == 2">
              <el-form-item label="统一社会信用代码" prop="orderLessee.USCC">
                <el-input
                  placeholder="请输入"
                  v-model="form.orderLessee.USCC"
                  style="width: 80%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="姓名" prop="orderLessee.lesseeName">
                <el-input
                  placeholder="请输入"
                  v-model="form.orderLessee.lesseeName"
                  style="width: 80%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="手机" prop="orderLessee.phone">
                <el-input
                  v-input.num
                  placeholder="请输入"
                  v-model="form.orderLessee.phone"
                  style="width: 80%"
                  maxlength="11"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="form.orderLessee.lesseeType == 1">
              <el-form-item label="身份证号" prop="orderLessee.cardNumber">
                <el-input
                  placeholder="请输入"
                  v-model="form.orderLessee.cardNumber"
                  style="width: 80%"
                  maxlength="18"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="8" v-if="form.orderLessee.lesseeType == 1">
              <el-form-item label="证件照片" prop="reserveUser">
                <el-button
                  @click="dialogVisible = true"
                  icon="el-icon-plus"
                  v-if="!form.orderLessee.cardImgsList||form.orderLessee.cardImgsList.length < 1"
                  >添加证件照片</el-button
                >
                <el-button @click="dialogVisible = true" type="primary" v-else
                  >编辑证件照片</el-button
                >
              </el-form-item>
            </el-col>
          </el-row>
          <el-descriptions title="租住信息"></el-descriptions>

          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="成交方式" prop="">
                <el-select
                  v-model="form.tradingMode"
                  placeholder=""
                  :disabled="true"
                >
                <el-option
            v-for="dict in dict.type.trading_mode"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="16" style="display: flex">
              <el-form-item label="租住周期" prop="checkInTime">
                <el-date-picker
                  :disabled="subletTime != ''||changeInfo.realityCheckOutTime"
                  v-model="form.checkInTime"
                  value-format="yyyy-MM-dd HH:ss:mm"
                  align="right"
                  type="date"
                  placeholder="开始日期"
                  :picker-options="startTimeOptions"
                  style="margin-right: 10px"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="" label-width="0" prop="checkOutTime">
                <el-date-picker
                  :disabled="subletTime != ''"
                  v-model="form.checkOutTime"
                  value-format="yyyy-MM-dd HH:ss:mm"
                  align="right"
                  type="date"
                  placeholder="结束日期"
                  :picker-options="endTimeOptions"
                  style="margin-right: 10px"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="免租天数" prop="freeRentNumber">
                <el-input
                  placeholder="请输入"
                  v-model.number="form.freeRentNumber"
                  type="number"
                >
                </el-input>
                <div v-show="form.freeRentNumber" style="color: red;" >免租周期：{{ form.checkInTime|formatDate("YYYY-MM-DD") }}至{{ getNextDate(form.checkInTime, form.freeRentNumber) }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="租赁方式" prop="rentalMode">
                <el-radio-group v-model="form.rentalMode">
                  <el-radio label="1">月租</el-radio>
                  <el-radio label="2">日租</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="8" v-if="form.rentalMode == 1" style="display: flex">
              <el-form-item label="押付方式" prop="depositNumber">
                <el-select
                  v-model="form.depositNumber"
                  placeholder=""
                  style="width: 120px"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="" label-width="0" prop="payNumber">
                <el-select
                  v-model="form.payNumber"
                  placeholder=""
                  style="width: 120px"
                >
                  <el-option
                    v-for="item in payoptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="form.rentalMode == 2">
              <el-form-item label="总租金" prop="totalRent">
                <el-input
                  v-input.num
                  placeholder="请输入"
                  v-model="form.totalRent"
                  style="width: 80%"
                  v-input.float="2"
                >
                  <span slot="append">元</span>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="8" v-if="form.rentalMode == 1">
              <el-form-item label="月租金" prop="monthRent">
                <el-input
                  v-input.num
                  placeholder="请输入"
                  v-model="form.monthRent"
                  v-input.float="2"
                >
                  <span slot="append">元/月</span>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="押金" prop="deposit">
                <el-input
                  v-input.num
                  placeholder="请输入"
                  v-model="form.deposit"
                  v-input.float="2"
                >
                  <span slot="append">元</span>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </div>
    </el-dialog>
    <!-- 选择房间 -->
    <SelectHouse
      v-model="dialogSelectHouseVisible"
      :filterId="form.houseId"
      @success="selectHouseCb"
      :vacancy="true"
    />

    <el-dialog title="证件照片" :visible.sync="dialogVisible" width="800px">
      <div style="display: flex">
        <div
          v-for="(item, index) in form.orderLessee.cardImgsList"
          :key="index"
          class="item-img-box"
        >
          <img class="up-img" :src="item" alt="" />
          <span class="item-delete">
            <span @click="handleRemove(index)">
              <i class="el-icon-delete"></i>
            </span>
          </span>
        </div>
        <el-upload
          action="/api/common/upload"
          list-type="picture-card"
          :auto-upload="true"
          :headers="headers"
          :accept="'image/*'"
          :on-success="onSuccess"
          :show-file-list="false"
        >
          <i slot="default" class="el-icon-plus"></i>
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import formRule from "@/utils/formRule.js";
import {getNextDate} from "@/utils/common/time.js";
import { getToken } from "@/utils/auth";
import {
  getOrderInfo,
  orderSign,
  exchangeHouse,
  relet,
  sublease,
} from "@/api/order/order";
import SelectHouse from "@/views/long-short-rent/contract/list/components/select-house.vue";
export default {
  name: "signOrder",
  dicts: ["trading_mode"],
  components: {
    SelectHouse,
  },
  props: {
    title: {
      default: "签约",
    },
    value: {
      default: false,
    },
    orderId: {
      default: undefined,
    },
    isDetail: {
      default: false,
    },
    success: {
      type: Function,
      default: () => {},
    },
    //转租时间
    subletTime: {
      type: String,
      default: "",
    },
    //换房参数，有则为换房
    changeInfo: {
      type: Object,
      default: {},
    },
    //是否续租
    isRelet: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      visible: false,
      dialogSelectHouseVisible: false,
      dialogVisible: false,
      oldOrder: {},
      headers: {
        Authorization: "Bearer " + getToken(),
        ["X-Tenantid"]: 1,
      },
      options: [
        {
          value: 1,
          label: "押一",
        },
        {
          value: 2,
          label: "押二",
        },
        {
          value: 3,
          label: "押三",
        },
        {
          value: 4,
          label: "押四",
        },
        {
          value: 5,
          label: "押五",
        },
        {
          value: 6,
          label: "押六",
        },
        {
          value: 7,
          label: "押七",
        },
        {
          value: 8,
          label: "押八",
        },
        {
          value: 9,
          label: "押九",
        },
        {
          value: 10,
          label: "押十",
        },
        {
          value: 11,
          label: "押十一",
        },
        {
          value: 12,
          label: "押十二",
        },
      ],
      payoptions: [
        {
          value: 1,
          label: "付一",
        },
        {
          value: 2,
          label: "付二",
        },
        {
          value: 3,
          label: "付三",
        },
        {
          value: 4,
          label: "付四",
        },
        {
          value: 5,
          label: "付五",
        },
        {
          value: 6,
          label: "付六",
        },
        {
          value: 7,
          label: "付七",
        },
        {
          value: 8,
          label: "付八",
        },
        {
          value: 9,
          label: "付九",
        },
        {
          value: 10,
          label: "付十",
        },
        {
          value: 11,
          label: "付十一",
        },
        {
          value: 12,
          label: "付十二",
        },
      ],
      form: {
        orderId: "",
        houseId: "",
        orderState: "1",
        orderTab: "1",
        reserveUser: "", //预订人
        reserveUserPhone: "", //预订人手机号
        deptId: null,
        checkInTime: "", //入住时间
        checkOutTime: "", //退房时间
        realityCheckInTime: null,
        realityCheckOutTime: null,
        finallySignTime: "",
        rentPaidNumber: null, //已付租金
        depositPaidNumber: null, //已付押金
        orderSource: "1", //订单来源
        orderType: "1", //订单类型
        tradingMode: "1", //成交方式
        linkedOrderId: null,
        freeRentNumber: null, //免租天数
        rentalMode: "1", //租赁方式
        depositNumber: null, //押几
        payNumber: null, //付几
        deposit: null, //押金
        monthRent: null, //月租金
        totalRent: null, //总租金
        orderLessee: {
          lesseeType: "1", //承租人类型：1个人 2企业
          lesseeName: "", //承租人姓名
          cardNumber: "", //身份证号
          enterpriseName: "", //企业名称
          phone: "", //手机号
          USCC: "", //社会统一信用代码
          cardImgsList: [], //证件照片
        },
      },
      areaCalculateState: false,
      chargeItemList: [],
      chargeItemSelected: [],
      startTimeOptions:{
        disabledDate: (time) => {
          return time.getTime() > new Date(this.form.checkOutTime);
        },
      },
      endTimeOptions: {
        disabledDate: (time) => {
          return time.getTime() < new Date(this.form.checkInTime);
        },
        shortcuts: [
          {
            text: "一个月",
            onClick: (picker) => {
              let date;
              if (this.form.checkInTime) {
                date = new Date(this.form.checkInTime);
              } else {
                date = new Date();
              }

              date.setTime(date.getTime() + 3600 * 1000 * 24 * 30);
              picker.$emit("pick", date);
            },
          },
          {
            text: "三个月",
            onClick: (picker) => {
              let date;
              if (this.form.checkInTime) {
                date = new Date(this.form.checkInTime);
              } else {
                date = new Date();
              }

              date.setTime(date.getTime() + 3600 * 1000 * 24 * 92);
              picker.$emit("pick", date);
            },
          },
          {
            text: "六个月",
            onClick: (picker) => {
              let date;
              if (this.form.checkInTime) {
                date = new Date(this.form.checkInTime);
              } else {
                date = new Date();
              }

              date.setTime(date.getTime() + 3600 * 1000 * 24 * 183);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一年",
            onClick: (picker) => {
              let date;
              if (this.form.checkInTime) {
                date = new Date(this.form.checkInTime);
              } else {
                date = new Date();
              }

              date.setTime(date.getTime() + 3600 * 1000 * 24 * 365);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      rules: {
        premisesAddress: [
          { required: true, message: "请选择房间", trigger: "change" },
        ],
        ["orderLessee.phone"]: [
          { required: true, message: "请输入手机", trigger: "blur" },
        ],
        tenantType: [
          { required: true, message: "请选择身份", trigger: "blur" },
        ],
        ["orderLessee.enterpriseName"]: [
          { required: true, message: "请输入企业名称", trigger: "blur" },
        ],
        totalRent: [
          {
            required: true,
            text: "number",
            message: "请输入总租金",
            trigger: "blur",
          },
        ],
        socialCreditNumber: [
          {
            required: true,
            message: "请输入统一社会信用代码",
            trigger: "blur",
          },
        ],
        freeRentNumber: [
          // {
          //   required: true,
          //   validator: (rule, value, callback) => {
          //     if (/^(?:[1-9]\d*)$/.test(value) == false) {
          //       callback(new Error("请输入正整数"));
          //     } else {
          //       callback();
          //     }
          //   },
          //   trigger: "blur",
          // },
        ],
        monthRent: [
          {
            required: true,
            message: "请输入月租金",
            trigger: "blur",
          },
        ],
        deposit: [
          {
            required: true,
            message: "请输入押金",
            trigger: "blur",
          },
        ],
        depositNumber: [
          {
            required: true,
            message: "请选择押付方式",
            trigger: "change",
          },
        ],
        payNumber: [
          {
            required: true,
            message: "请选择押付方式",
            trigger: "change",
          },
        ],
        ["orderLessee.lesseeName"]: [
          {
            required: true,
            message: "请输入姓名",
            trigger: ["change", "blur"],
          },
        ],
        ["orderLessee.phone"]: [
          { required: true, message: "请输入电话", trigger: "blur" },
          {
            validator: formRule.phone,
            message: "",
            trigger: ["change", "blur"],
          },
        ],
        sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
        ["orderLessee.cardNumber"]: [
          { required: true, message: "请输入身份证号", trigger: "blur" },
          {
            validator: formRule.IDCard,
            message: "",
            trigger: ["change", "blur"],
          },
        ],
        ["orderLessee.lesseeType"]: [
          { required: true, message: "请选择签约方式", trigger: "change" },
        ],
        checkInTime: [
          { required: true, message: "请输入入住日期", trigger: "blur" },
        ],
        checkOutTime: [
          { required: true, message: "请输入退房日期", trigger: "blur" },
        ],
        finallySignTime: [
          { required: true, message: "请选择最晚签约日期", trigger: "blur" },
        ],
        paymentType: [
          { required: true, message: "请选择付款方式", trigger: "blur" },
        ],
        payTypeId: [
          { required: true, message: "请选择押付方式", trigger: "change" },
        ],
        cleaningType: [
          {
            required: true,
            message: "请选择是否购买保洁费",
            trigger: "change",
          },
        ],
        cleaningPrice: [
          { required: true, message: "请输入保洁费", trigger: "blur" },
        ],
        priceAmounts: [
          { required: true, message: "请输入总金额", trigger: "blur" },
        ],
        depositPaidNumber: [
          { required: true, message: "请输入押金", trigger: "blur" },
        ],
        rentPaidNumber: [
          { required: true, message: "请输入租金", trigger: "blur" },
        ],
        billingDate: [
          { required: true, message: "请输入号数", trigger: "blur" },
        ],
      },
    };
  },
  computed: {},
  watch: {

  },
  mounted() {
    this.getInfo()
  },
  methods: {
    getNextDate:getNextDate,
    handleRemove(index) {
      this.form.orderLessee.cardImgsList.splice(index, 1);
    },
    onSuccess(response, file, fileList) {
      this.form.orderLessee.cardImgsList.push(response.url);
    },
    //日期更改
    periodChange(e) {
      this.form.checkInTime = e[0] + " 00:00:00";
      this.form.checkOutTime = e[1] + " 23:59:00";
    },
    finallySignChange(e) {
      this.form.finallySignTime = e + " 23:59:00";
    },
    //重置表单
    reset() {
      this.form = this.$options.data().form;
    },
    //获取详情
    getInfo() {

      if (!this.orderId) return;
      getOrderInfo(this.orderId).then((response) => {
        let form = response.data;
        this.oldOrder = response.data;
        let changeInfo = this.changeInfo;
        this.form = form;
        let orderLessee = {
          lesseeType: "1", //承租人类型：1个人 2企业
          lesseeName: form.reserveUser, //承租人姓名
          cardNumber: "", //身份证号
          enterpriseName: "", //企业名称
          phone: form.reserveUserPhone, //手机号
          USCC: "", //社会统一信用代码
          cardImgsList: [], //证件照片
        };
        if(!form.orderLessee){
          form.orderLessee = orderLessee;
        }
        if(!form.tradingMode){
          form.tradingMode='1'
        }
        if(!form.rentalMode){
          form.rentalMode='1'
        }
        this.form=form
        let houseObj = {
          houseId: changeInfo.changeHouseId
            ? changeInfo.changeHouseId
            : form.houseId, //房屋id
          premisesAddress: changeInfo.changePremisesAddress
            ? changeInfo.changePremisesAddress
            : form.premisesAddress, //小区地址
        };
        this.form = { ...this.form, ...houseObj };
        //换房
        if (this.changeInfo.changeHouseId) {
          this.form.realityCheckOutTime = this.changeInfo.realityCheckOutTime;
          this.form.checkInTime =
            getNextDate(this.changeInfo.realityCheckOutTime, 1) + " 00:00:00";
          this.form.checkOutTime = "";
          this.form.tradingMode='2';
        }
        //转租
        if (this.subletTime) {
          this.form.realityCheckOutTime = this.subletTime;
          this.form.checkInTime =
            getNextDate(this.subletTime, 1) + " 00:00:00";
            this.form.tradingMode='4';
        }
        //续租
        if (this.isRelet) {
          this.form.checkInTime = getNextDate(null, 0) + " 00:00:00";
          this.form.checkOutTime = "";
          this.form.tradingMode='3';
        }
      });
    },
    //房间选择回调
    selectHouseCb(data) {
      let houseObj = {
        houseId: "", //房屋id
        premisesAddress: null, //小区地址
      };
      for (const key in houseObj) {
        houseObj[key] = data[key];
      }
      this.form = { ...this.form, ...houseObj };
    },
    //提交表单
    submitForm: function () {
      let houseObj = {
        provinceId: "", //省
        provinceName: "", //省份名称
        cityId: "", //市
        cityName: "", //市名称
        districtId: "", //区
        districtName: "", //区名称
        streetId: "", //所属街道
        streetName: "", //街道名称
        communityId: "", //所属社区
        communityName: "", //所属社区名称
        fullAddress:'',
        roomNumber: "", //房间号
        estateId: "", //楼盘id
        estateName: "", //楼盘名称
        buildingId: "", //楼栋id
        buildingName: "", //楼栋名称
        unitId: "", //单元id
        unitName: "", //单元名称
        floors: undefined, //层数
      };
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.subletTime) {
            this.oldOrder.order = this.form;
            delete this.oldOrder.order.orderId;
            for (const key in houseObj) {
              delete this.oldOrder.order[key];
            }
            this.oldOrder.realityCheckOutTime=this.subletTime;
            sublease(this.oldOrder).then((response) => {
              this.$emit("success");
              this.$message.success("转租成功");
              this.close();
            });
          } else if (this.isRelet) {
            this.oldOrder.order = this.form;
            delete this.oldOrder.order.orderId;
            for (const key in houseObj) {
              delete this.oldOrder.order[key];
            }
            this.oldOrder.realityCheckOutTime=this.form.checkInTime;
            relet(this.oldOrder).then((response) => {
              this.$emit("success");
              this.$message.success("续租成功");
              this.close();
            });
          } else if (this.changeInfo.changeHouseId) {
            this.oldOrder.order = this.form;
            delete this.oldOrder.order.orderId;
            for (const key in houseObj) {
              delete this.oldOrder.order[key];
            }
            this.oldOrder.realityCheckOutTime=this.form.checkInTime;
            exchangeHouse(this.oldOrder).then((response) => {
              this.$emit("success");
              this.$message.success("换房签约成功");
              this.close();
            });
          } else {
            orderSign(this.form).then((response) => {
              this.$emit("success");
              this.$message.success("签约成功");
              this.close();
            });
          }
        }
      });
    },
    //关闭
    close() {
      this.$emit("input", false);
    },
  },
};
</script>

<style lang="scss" scoped>
.import-dialog {
  height: auto;
  max-height: 80vh;
  overflow-y: auto;
  .dialog-footer {
    text-align: center;
  }
}
::v-deep .el-dialog__body {
  max-height: 80vh !important;
  overflow-y: auto;
}
.form-box {
  .tabs {
    display: flex;
    .tabs-item {
      padding: 0 10px;
      height: 40px;
      line-height: 40px;
      font-size: 16px;
      position: relative;
      cursor: pointer;
      &::before {
        content: "";
        position: absolute;
        left: 50%;
        bottom: -2px;
        width: 0;
        height: 2px;
        opacity: 0;
        background: #0caaf0;
        transition: all 0.3s;
      }
      &.active {
        color: #0caaf0;
        &::before {
          opacity: 1;
          left: 0;
          width: 100%;
        }
        cursor: default;
      }
    }
  }
  .add-form {
    .section {
      .label {
        display: flex;
        margin-bottom: 20px;
        font-size: 16px;
        align-items: center;
        color: #303133;
        label {
          display: block;
          width: 80px;
          &.dot::before {
            content: "*";
            color: #ff4949;
            margin-right: 4px;
          }
        }
        .icon {
          color: #02a7f0;
          font-size: 30px;
          margin-left: 30px;
          cursor: pointer;
        }
      }
      .tips {
        color: #aaaaaa;
      }
      .custom-formItem-lable {
        display: flex;
        align-items: center;
        .handle-icon {
          color: #02a7f0;
          font-size: 30px;
          margin-left: 30px;
          cursor: pointer;
        }
      }
      .handle-icon {
        color: #02a7f0;
        font-size: 30px;
        cursor: pointer;
      }
    }
  }
}
.item-img-box {
  position: relative;
  border: 1px solid #aaaaaa;
  width: 148px;
  height: 148px;
  margin-right: 10px;
  border-radius: 4px;
  overflow: hidden;
  .up-img {
    width: 148px;
    height: 148px;
  }
  .item-delete {
    position: absolute;
    left: 50%;
    top: 50%;
    z-index: 99;
    transform: translate(-50%, -50%);
    font-size: 32px;
    color: #ff4949;
    cursor: pointer;
  }
}
</style>
